<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree v-bind:tree-data="treeData"
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>用户账号：<el-input placeholder="请输入用户账号" v-model="queryData.username" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>用户姓名：<el-input placeholder="请输入用户姓名" v-model="queryData.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>

        <el-main>
          <app-table :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows"
            v-on:checkSingleRow="checkSingleRow"
            v-on:changeSingleRow="changeSingleRow"
            v-on:deleSingleRow="deleSingleRow" />
          <el-dialog title="用户配置"
            :visible.sync="dialogFormVisible"
            :before-close="close">
            <el-form :model="formData"
              :rules="rules"
              ref="formData"
              :disabled="showOnly"
              label-width="120px"
              size="mini">
              <el-row>
                <el-col :span="12">
                <el-form-item label="所属网格" prop="gridIdArr">
                  <!-- <grid-cascader v-model="formData.allGridId"></grid-cascader> -->
                  <el-input v-model="formData.gridName" readonly></el-input>
                  <!-- <div class="block">
                    <el-cascader placeholder="请选择"
                      :options="treeOption"
                      filterable
                      clearable
                      :props="gridIdProps"
                      v-model="formData.allGridId"
                      change-on-select>
                    </el-cascader>
                  </div> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="网格编号" prop="gridIdCode">
                  <el-input v-model="formData.gridIdCode" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="网格员类型" prop="memberType">
                  <el-select filterable v-model="formData.memberType" placeholder="请选择网格员类型">
                    <el-option v-for="item in gridMemberType"
                      :key="item.id"
                      :value="item.value"
                      :label="item.label"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户" prop="userId">
                  <el-select filterable v-model="formData.userId" @change="handleBlur" @focus="handleFocus"  placeholder="请选择用户">
                    <el-option v-for="item in allUserDataArr"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name+':'+item.username"></el-option>
                  </el-select>
                  <el-button v-if='!showInput' @click="addDialog">新增</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="showInput">
                  <el-form-item label="姓名：" prop="name">
                    <el-input v-model="addFormData.name" placeholder="请输入姓名"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12"  v-if="showInput">
                  <el-form-item label="身份证号：" prop="idCardNumber">
                    <el-input v-model="addFormData.idCardNumber" placeholder="请输入身份证号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12"  v-if="showInput">
                  <el-form-item label="性别：">
                    <el-select v-model="addFormData.sex" placeholder="请选择性别">
                      <el-option v-for="(item,index) in genderOptions" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12"  v-if="showInput">
                  <el-form-item label="工号：">
                    <el-input v-model="addFormData.jobNumber" placeholder="请输入工号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12"  v-if="showInput">
                  <el-form-item label="电话：">
                    <el-input v-model="addFormData.phone" placeholder="请输入电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12"  v-if="showInput">
                  <el-form-item label="邮箱：">
                    <el-input v-model="addFormData.email" placeholder="请输入邮箱"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12"  v-if="showInput">
                  <el-form-item label="联系地址：">
                    <el-input v-model="addFormData.address" placeholder="请输入联系地址"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12"  v-if="showInput">
                  <el-form-item label="政治面貌：">
                    <el-select v-model="addFormData.politicsStatus" clearable placeholder="请选择" filterable>
                      <el-option v-for="(item,index) in politicalStatusOption" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button v-if="showInput" type='danger' @click="cancelAsso">取消关联</el-button>
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary" @click="save('formData')">提 交</el-button>
            </div>
          </el-dialog>
          <el-dialog title="新增用户" :visible.sync="dialogFormVisible2" :before-close="closeUser" :close-on-click-modal="false">
            <el-form :model="addFormData"
             :rules="rules"
             ref="addFormData"
             :disabled="showOnly"
             label-width="120px"
             size="mini">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="部门：" prop="deptIdArr">
                    <div class="block">
                      <el-cascader
                        placeholder="请选择"
                        :options="treeDataDept"
                        clearable
                        filterable
                        :props="areaProps"
                        change-on-select
                        :show-all-levels="false"
                        v-model="addFormData.deptIdArr"
                        >
                      </el-cascader>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="账号：" prop="username">
                    <el-input v-model="addFormData.username" placeholder="请输入账号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="姓名：" prop="name">
                    <el-input v-model="addFormData.name" placeholder="请输入姓名"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="身份证号：" prop="idCardNumber">
                    <el-input v-model="addFormData.idCardNumber" placeholder="请输入身份证号"
                    :rules="[{required:true,validator: validateIdefer,message: '请输入有效身份证号', trigger: 'blur'}]">
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="性别：">
                    <el-select v-model="addFormData.sex" placeholder="请选择性别">
                      <el-option v-for="(item,index) in genderOptions" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="工号：">
                    <el-input v-model="addFormData.jobNumber" placeholder="请输入工号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="电话：">
                    <el-input v-model="addFormData.phone" placeholder="请输入电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="邮箱：">
                    <el-input v-model="addFormData.email" placeholder="请输入邮箱"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="联系地址：">
                    <el-input v-model="addFormData.address" placeholder="请输入联系地址"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!showInput">
                  <el-form-item label="政治面貌：">
                    <el-select v-model="addFormData.politicsStatus" clearable placeholder="请选择" filterable>
                      <el-option v-for="(item,index) in politicalStatusOption" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button @click="cancel('addFormData')">取 消</el-button>
              <el-button type="primary" @click="saveUser('addFormData')">提 交</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import {getUserGridTree} from '@/utils/LocalDataUtil'
import {getUserDeptTree} from '@/utils/SessionDataUtil'
import {getLastIdByAllId} from '@/utils/CommonUtil'
import GridCascader from '@/components/GridCascader'
import { getAllRegionObj } from '@/utils/region'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {validateIdefer} from '@/utils/validate'

import {
  createGridMember,
  findGridMember,
  // updateGridMember,
  deleteGridMember,
  getUserListDepart,
  // getUserList,
  createUser,
  updateUser,
  getUser
} from '@/http/AppApi'
export default {
  data () {
    return {
      btnShow: false,
      showInput: false,
      btnType: '',
      tableData: [],
      pageData: {},
      queryData: {},
      treeData: [],
      treeDataDept: [],
      allUserDataArr: [],
      formData: {},
      addFormData: {},
      areaProps: {
        label: 'name',
        value: 'id'
      },
      treeOption: [],
      allUserData: [],
      dialogTitle: '',
      dialogFormVisible: false,
      dialogFormVisible2: false,
      currentSelectedData: [],
      showOnly: false,
      showMap: false,
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      genderOptions: [],
      politicalStatusOption: [],
      tableColumns: [{
        label: '账号',
        prop: 'username'
      },
      {
        label: '名称',
        prop: 'name'
      },
      {
        label: '角色',
        prop: 'roleName'
      },
      {
        label: '网格员类型',
        prop: 'memberType',
        formatter: this.filterType
      },
      {
        label: '所属网格',
        prop: 'gridName'
      }
      ],
      gridMemberType: [{
        label: '网格员',
        value: 1
      },
      {
        label: '网格长',
        value: 0
      }
      ],
      rules: {
        gridId: [{
          required: true,
          message: '请选择网格员类型',
          trigger: 'blur'
        }],
        memberType: [{
          required: true,
          message: '请选择网格员类型',
          trigger: 'blur'
        }],
        userId: [{
          required: true,
          message: '请选择用户',
          trigger: 'blur'
        }],
        deptIdArr: [{
          required: true,
          message: '请选择部门',
          trigger: 'blur'
        }],
        username: [{
          required: true,
          message: '请输入账号',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        disableStatus: [{
          required: true,
          message: '请选择是否启用',
          trigger: 'blur'
        }]
      }
    }
  },
  components: {
    BtnGroup,
    AppTable,
    AppTree,
    GridCascader
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
    this.getTreeDataDept()
  },
  methods: {
    validateIdefer (rule, value, callback, flag) {
      validateIdefer(rule, value, callback, flag)
    },
    filterType (row, column) {
      if (row.memberType === 0) {
        return '网格长'
      } else if (row.memberType === 1) {
        return '网格员'
      } else {
        return ''
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formData) {
            if (!this.beforeSubmit()) {
              return
            }
            if (this.formData.id) {
              let d = this.addFormData
              updateUser(d).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.getTreeData()
                  this.cancel(formName)
                  this.$message({
                    type: 'success',
                    message: '修改成功'
                  })
                }
              })
            } else {
              let d = this.formData
              createGridMember(d).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.getTreeData()
                  this.cancel(formName)
                  this.$message({
                    type: 'success',
                    message: '新增成功'
                  })
                }
              })
            }
          }
        } else {
          return false
        }
      })
    },
    saveUser (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$set(this.addFormData, 'disableStatus', 1)
          if (this.addFormData.deptIdArr && this.addFormData.deptIdArr.length > 0) {
            let len = this.addFormData.deptIdArr.length - 1
            this.$set(this.addFormData, 'departmentId', this.addFormData.deptIdArr[len])
          } else {
            this.$set(this.addFormData, 'departmentId', '')
          }
          if (this.addFormData.id) {
            updateUser(this.addFormData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.cancel(formName)
                this.getTableData()
                this.$message({
                  showClose: true,
                  message: '修改成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  type: 'warning',
                  message: resp.message
                })
              }
            })
          } else {
            createUser(this.addFormData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.getTableData()
                this.dialogFormVisible = false
                this.cancel(formName)
                this.$message({
                  showClose: true,
                  message: '新增成功',
                  type: 'success'
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteGridMember(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
              }
            })
          })
        }).catch(() => {
          this.$message({
            message: '已取消删除'
          })
        })
      }
    },
    cancelAsso () {
      let row = this.formData
      deleteGridMember(row).then(resp => {
        if (resp.code && resp.code === '200') {
          this.getTableData()
          this.dialogFormVisible = false
          this.cancel('addFormData')
          this.$message({
            type: 'success',
            message: '取消关联成功'
          })
        }
      })
    },
    cancel (formName) {
      this.dialogFormVisible = false
      this.dialogFormVisible2 = false
      this.formData = {}
      this.addFormData = {}
      this.allUserDataArr = []
      this.showMap = false
      this.btnShow = false
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },
    close () {
      this.dialogFormVisible = false
      this.dialogFormVisible2 = false
      this.formData = {}
      this.addFormData = {}
      this.showMap = false
      this.allUserDataArr = []
      this.btnShow = false
      this.$refs['formData'].resetFields()
    },
    closeUser () {
      this.dialogFormVisible = false
      this.dialogFormVisible2 = false
      this.formData = {}
      this.allUserDataArr = []
      this.showMap = false
      this.btnShow = false
      this.$refs['addFormData'].resetFields()
    },
    addDialog () {
      this.dialogFormVisible = false
      this.dialogFormVisible2 = true
      this.formData = {}
      this.allUserDataArr = []
      this.showMap = false
      this.btnShow = false
      this.$refs['formData'].resetFields()
    },
    getTableData () {
      let param = this.queryData
      findGridMember(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            this.$set(this.pageData, 'isCommonDo', true)
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        }
      })
    },
    beforeSubmit () {
      if (this.formData.allGridId) {
        this.formData.gridId = getLastIdByAllId(this.formData.allGridId)
      }
      return true
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
        this.treeOption = data
      }
    },
    getTreeDataDept () {
      let data = getUserDeptTree()
      if (data && data instanceof Array) {
        this.treeDataDept = data
      }
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.gridId = data.id
      this.getTableData()
      this.$set(this.formData, 'gridId', data.id)
      let regionData = {}
      regionData.id = data.id
      regionData.items = this.treeData
      let temp = getAllRegionObj(regionData)
      this.$set(this.formData, 'gridName', temp[temp.length - 1].name)
      this.$set(this.formData, 'gridIdCode', temp[temp.length - 1].gridCode)
      this.getAllUserData(data.id)
    },
    btnClickCallback (callbackData) {
      this.btnType = callbackData.btnType
      this.genderOptions = getDictDataOption('性别')
      this.politicalStatusOption = getDictDataOption('政治面貌')
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
        if (callbackData.btnType === 'post') {
          this.showInput = false
          if (!this.formData.gridName) {
            this.dialogFormVisible = false
            this.$message({
              type: 'warning',
              message: '请先选择网格'
            })
          }
          // this.formData = this.formData.gridId ? this.formData : {}
        } else if (callbackData.btnType === 'add_user') {
          this.dialogFormVisible2 = true
          this.dialogFormVisible = false
        } else {
          this.dialogFormVisible2 = false
          this.dialogFormVisible = true
          this.showInput = true
          let rowData = callbackData.rows[0]
          if (rowData) {
            this.formData = JSON.parse(JSON.stringify(rowData))
            this.handleBlur(this.formData.userId)
            let regionData = {}
            regionData.id = this.formData.gridId
            this.getAllUserData(this.formData.gridId)
            regionData.items = this.treeData
            let temp = getAllRegionObj(regionData)
            this.$set(this.formData, 'gridIdCode', temp[temp.length - 1].gridCode)
          }
        }
      }
    },
    checkSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    changeSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    deleSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      }
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    getAllUserData (id) {
      getUserListDepart(id).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            this.allUserData = data
            this.allUserDataArr = data
          }
        }
      })
      // getUserList().then(resp => {
      //   if (resp.code && resp.code === '200') {
      //     let data = resp.data
      //     if (data && data instanceof Array) {
      //       this.allUserData = data
      //       this.allUserDataArr = data
      //     }
      //   }
      // })
    },
    handleFocus () {
      this.allUserDataArr = this.allUserData
    },
    handleBlur (e) {
      getUser(e).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.addFormData = data
        }
      })
    },
    searchBack (val) {
      val = val.toString()
      if (val) {
        this.allUserDataArr = this.allUserData.filter((item) => {
          if (!!~item.name.indexOf(val) || !!~item.name.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          } else {
            return false
          }
        })
      } else {
        this.allUserDataArr = this.allUserData
      }
      if (this.allUserDataArr.length > 0) {
        this.btnShow = false
      } else {
        this.btnShow = true
      }
    }
  },
  computed: {},
  watch: {}
}
</script>
<style scoped>
.el-form >>> .el-form-item__error {
  margin-top: 2px;
}
</style>
